package com.yiwei.zhh.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.yiwei.zhh.R;
import com.yiwei.zhh.api.callback.ShareIndexContract;
import com.yiwei.zhh.api.requestInfo.ShareIndexRequest;
import com.yiwei.zhh.model.ShareIndexModel;
import com.yiwei.zhh.util.QRCode;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.UI;
import com.yiwei.zhh.view.V19FrameLayout;

import org.sufficientlysecure.htmltextview.HtmlTextView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 2017/6/7.
 */

public class V3InviteFriendsActivity extends BaseActivity implements ShareIndexContract.View {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_copy)
    SuperButton btnCopy;
    @BindView(R.id.btn_save)
    SuperButton btnSave;
    @BindView(R.id.txt_rule)
    HtmlTextView txtRule;

    private Unbinder unbiner;
    private ShareIndexRequest api;
    private String textCopy;
    private Spanned spanned;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_v3_invite_friends);
        initBar();
        unbiner = ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        txtTitle.setText("邀请好友");
        txtRight.setText("我的奖励");
        txtRight.setVisibility(View.VISIBLE);
        api = ShareIndexRequest.create();
        api.attachView(this);
        api.getShareIndex();
    }

    private String title;
    private String content;
    private String url;
    private String imageUrl;


    //Glide保存图片
    public void savePicture(String url) {
        saveImageToGallery(V3InviteFriendsActivity.this, QRCode.createQRCode(url));

    }

    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "hmx");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        ToastUtil.makeText(context, "保存成功").show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        unbiner.unbind();
        unbiner = null;
        api.detachView();
        api = null;
        spanned = null;
    }

    @Override
    public void showError() {
        loadingDialog.dismiss();
    }

    @Override
    public void complete() {
        loadingDialog.dismiss();
    }

    @Override
    public void onRequestStart() {
        loadingDialog.show();
    }

    @Override
    public void getShareIndexSuccess(ShareIndexModel item) {
        ShareIndexModel.Data.Share share = item.data.share;
        title = share.title;
        content = share.description;
        url = share.url;
        imageUrl = share.image;
//        List<ShareIndexModel.Data.Rule> rules = item.data.rules;
//
//
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < rules.size(); i++) {
//            setSpanTitle(rules.get(i).title, sb);
//            setSpanContent(rules.get(i).desc, sb);
//        }
//        spanned = Html.fromHtml(sb.toString());
        if (!TextUtils.isEmpty(item.data.rulesHtml)) {
            txtRule.setHtml(item.data.rulesHtml);

        }


    }

    public void setSpanTitle(String title, StringBuilder sb) {
        sb.append("<fon><big>");
        sb.append(title);
        sb.append("</big></font><br/>");
    }

    public void setSpanContent(String content, StringBuilder sb) {
        sb.append("<font color=\"#5B5F8E\">");
        sb.append(content);
        sb.append("</font><br/><br/>");
    }

    @OnClick({R.id.btn_back, R.id.txt_right, R.id.btn_copy, R.id.btn_save})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_copy:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", url);
// 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtil.makeText(this, "复制成功").show();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_save:
                if (TextUtils.isEmpty(url)) {
                    return;
                }
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        savePicture(url);
                    }

                    @Override
                    public void superReject() {

                    }
                }, R.string.camera_storage_card_p, R.string.ask_again, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;


            case R.id.txt_right:
                if (TextUtils.isEmpty(title)) {
                    api.getShareIndex();
                    return;
                }
                Intent intent = new Intent(this, InviteRecordActivity.class);
                intent.putExtra("title", title);
                intent.putExtra("content", content);
                intent.putExtra("url", url);
                intent.putExtra("imageUrl", imageUrl);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }
    }

}
